package com.maodou.core.network

import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit

object NetworkFactory {

    fun createMoshi(customize: (Moshi.Builder.() -> Unit)? = null): Moshi {
        val builder = Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
        if (customize != null) builder.customize()
        return builder.build()
    }

    fun createOkHttpClient(config: HttpConfig): OkHttpClient {
        val builder = OkHttpClient.Builder()
            .connectTimeout(config.connectTimeoutSec, TimeUnit.SECONDS)
            .readTimeout(config.readTimeoutSec, TimeUnit.SECONDS)
            .writeTimeout(config.writeTimeoutSec, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)

        config.headerProvider?.let { builder.addInterceptor(HeaderInterceptor(it)) }
        builder.addInterceptor(UnauthorizedInterceptor(config.unauthorizedHandler))
        
        config.interceptors.forEach { builder.addInterceptor(it) }
        config.networkInterceptors.forEach { builder.addNetworkInterceptor(it) }

        if (config.isDebug) {
            val logging = HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            }
            builder.addInterceptor(logging)
        }

        return builder.build()
    }

    fun createRetrofit(
        config: HttpConfig,
        okHttpClient: OkHttpClient = createOkHttpClient(config),
        moshi: Moshi = createMoshi()
    ): Retrofit {
        return Retrofit.Builder()
            .baseUrl(config.baseUrl)
            .client(okHttpClient)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .build()
    }
}